﻿using yuanna.Common;
using yuanna.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.Devices.Geolocation;

// “透视应用程序”模板在 http://go.microsoft.com/fwlink/?LinkID=391641 上有介绍

namespace yuanna
{
    public sealed partial class PivotPage : Page
    {
        private const string DataName = "YuannaData";

        private readonly NavigationHelper navigationHelper;
        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();
        private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources");

        #region
        StatusBarProgressIndicator _prog;

        DispatcherTimer _timer;
        DateTime _startTime;
        TimeSpan _durationTime = new TimeSpan(0);
        TimeSpan _pauseTime = new TimeSpan(0);
        Point _beforePoint;
        double _distance;
        double _speed;

        YuannaPath _currentYuannaPath;
        Geolocator _geo;
        bool _isTracking = false;
        int _pauseCount = 0;

        string _appTitle;
        string _statusUnstartOrStopedText;
        string _statusPausedText;
        string _statusDisabled;
        string _statusInitializing;
        string _statusNoData;
        string _statusReady;
        string _statusNotAvailable;
        string _statusText;

        Color _statusUnstartOrStopedColor = Colors.Brown;
        Color _statusTrackingColor = Colors.Green;
        Color _statusPauseColor = Colors.Purple;
        Color _statusColor;
        #endregion

        public PivotPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            _appTitle = this.resourceLoader.GetString("AppName");
            _statusUnstartOrStopedText = this.resourceLoader.GetString("StatusUnstartOrStoped");
            _statusPausedText = this.resourceLoader.GetString("StatusPaused");
            _statusDisabled = this.resourceLoader.GetString("StatusDisabled");
            _statusInitializing = this.resourceLoader.GetString("StatusInitializing");
            _statusNoData = this.resourceLoader.GetString("StatusNoData");
            _statusReady = this.resourceLoader.GetString("StatusReady");
            _statusNotAvailable = this.resourceLoader.GetString("StatusNotAvailable");

            this.ShowStatusBar();
        }

        public async void ShowStatusBar()
        {
            StatusBar statusBar = StatusBar.GetForCurrentView();
            statusBar.BackgroundColor = _statusUnstartOrStopedColor;
            statusBar.BackgroundOpacity = 1;
            statusBar.ForegroundColor = Colors.White;
            await statusBar.ShowAsync();

            statusBar.ProgressIndicator.Text = string.Concat(_appTitle, " - ", _statusUnstartOrStopedText);
            await statusBar.ProgressIndicator.ShowAsync();
        }

        /// <summary>
        /// 获取与此 <see cref="Page"/> 关联的 <see cref="NavigationHelper"/>。
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// 获取此 <see cref="Page"/> 的视图模型。
        /// 可将其更改为强类型视图模型。
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="sender">
        /// 事件的来源；通常为 <see cref="NavigationHelper"/>。
        /// </param>
        /// <param name="e">事件数据，其中既提供在最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数，又提供
        /// 此页在以前会话期间保留的状态的
        /// 的字典。首次访问页面时，该状态将为 null。</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: 创建适用于问题域的合适数据模型以替换示例数据
            var yuannaData = await YuannaDataSource.GetYuannaDataAsync();
            this.DefaultViewModel[DataName] = yuannaData;
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合序列化
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="sender">事件的来源；通常为 <see cref="NavigationHelper"/>。</param>
        ///<param name="e">提供要使用可序列化状态填充的空字典
        ///的事件数据。</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: 在此处保存页面的唯一状态。
        }

        /// <summary>
        /// 在单击应用程序栏按钮时将项添加到列表中。
        /// </summary>
        private void AddAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            var yuannaData = this.DefaultViewModel[DataName] as YuannaData;
            var nextId = yuannaData.YuannaPaths.Count + 1;
            var newPath = new YuannaPath(nextId.ToString(), 0, 1, "1", false, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));

            yuannaData.YuannaPaths.Add(newPath);

            // 将新的项滚动到视图中。
            var container = this.pivot.ContainerFromIndex(this.pivot.SelectedIndex) as ContentControl;
            var listView = container.ContentTemplateRoot as ListView;
            listView.ScrollIntoView(newPath, ScrollIntoViewAlignment.Leading);
        }

        /// <summary>
        /// 在单击节内的项时调用。
        /// </summary>
        private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // 导航至相应的目标页，并
            // 通过将所需信息作为导航参数传入来配置新页
            var itemId = ((YuannaPoint)e.ClickedItem).UniqueId;
            if (!Frame.Navigate(typeof(ItemPage), itemId))
            {
                throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
            }
        }

        #region NavigationHelper 注册

        /// <summary>
        /// 此部分中提供的方法只是用于使
        /// NavigationHelper 可响应页面的导航方法。
        /// <para>
        /// 应将页面特有的逻辑放入用于
        /// <see cref="NavigationHelper.LoadState"/>
        /// 和 <see cref="NavigationHelper.SaveState"/> 的事件处理程序中。
        /// 除了在会话期间保留的页面状态之外
        /// LoadState 方法中还提供导航参数。
        /// </para>
        /// </summary>
        /// <param name="e">提供导航方法数据和
        /// 无法取消导航请求的事件处理程序。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion
    }
}
